package com.example.poemtest.index.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.poemtest.Activity.BottomNavigationViewActivity;
import com.example.poemtest.R;
import com.example.poemtest.databinding.ActivityPoetryRelayBinding;
import com.example.poemtest.entity.PoetryInfoBean;
import com.example.poemtest.index.adapter.PoetryRelayAdapter;
import com.example.poemtest.index.entity.PoetryRelayBean;
import com.example.poemtest.index.entity.ProtryBean;
import com.example.poemtest.index.util.GetJsonDataUtil;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;
import com.google.gson.Gson;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 诗词接龙页面
 */
public class PoetryRelayActivity extends AppCompatActivity {

    private final static String TAG = "诗";

    private ActivityPoetryRelayBinding binding;

    private String chooseText = "";
//    private List<PoetryInfoBean.PoetryInfo> allMessageDataList;  //数据库
    private List<PoetryInfoBean.PoetryInfo> haveShowList;  //已用过的诗词列表

    PoetryRelayAdapter mDetailChatAdapter;  //主页adapter
    private List<PoetryInfoBean.PoetryInfo> showDataList;
    private int onPoetryNum = 0;
    private ImageView back;

    public static void start(Context context) {
        Intent starter = new Intent(context, PoetryRelayActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FullScreenUtil.getInstance().fullScreen(this,true);
        //初始化databinding
        binding = DataBindingUtil.setContentView(this, R.layout.activity_poetry_relay);
//        allMessageDataList = new ArrayList<>();
        showDataList = new ArrayList<>();
        haveShowList = new ArrayList<>();
//        initJsonData();
        back = findViewById(R.id.setup_safe_to_mine);

        mDetailChatAdapter = new PoetryRelayAdapter(this);
        binding.rv.setAdapter(mDetailChatAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(PoetryRelayActivity.this);
        linearLayoutManager.setStackFromEnd(true);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.rv.setLayoutManager(linearLayoutManager);
        mDetailChatAdapter.setLists(showDataList);

        binding.TvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("诗", "binding.EtMsgContent.getText().toString(): "+binding.EtMsgContent.getText().toString());
                if (TextUtils.isEmpty(binding.EtMsgContent.getText())){
                    Toast.makeText(PoetryRelayActivity.this,"请输入您的诗句",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (binding.EtMsgContent.getText().length()<2){
                    Toast.makeText(PoetryRelayActivity.this,"请输入2个字以上的诗句",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!TextUtils.isEmpty(chooseText)&&!binding.EtMsgContent.getText().toString().startsWith(chooseText)
                        &&(showDataList.size()>0&&!showDataList.get(showDataList.size()-1).isIsmyself())){
                    binding.EtMsgContent.getText().clear();
                    Toast.makeText(PoetryRelayActivity.this,"输入诗句不是以“" + chooseText + "”字打头。",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (haveShowList.size()>0){
                    for (PoetryInfoBean.PoetryInfo poetryInfo : haveShowList) {
                        if (StringUtils.contains(poetryInfo.getPoetryContent(),binding.EtMsgContent.getText().toString())){
                            binding.EtMsgContent.getText().clear();
                            Toast.makeText(PoetryRelayActivity.this,"输入诗句已重复",Toast.LENGTH_SHORT).show();
                            return;
                        }
                    }
                }
                PoetryInfoBean.PoetryInfo poetryRelayBean = new PoetryInfoBean.PoetryInfo();
                poetryRelayBean.setIsmyself(true);
                poetryRelayBean.setPoetryContent(binding.EtMsgContent.getText().toString());

                mDetailChatAdapter.addItem(poetryRelayBean);
                scrollBottom();
                Log.i("诗", "进度: ");
                //取最后一个文字
                String getContent = binding.EtMsgContent.getText().toString()
                        .replace("。","")
                        .replace("，","");
                chooseText = getContent.substring(getContent.length()-1,getContent.length());
                mDetailChatAdapter.setStartText(chooseText);
                binding.EtMsgContent.getText().clear();
                mhandler.sendEmptyMessageDelayed(0x124,1000);
                haveShowList.add(poetryRelayBean);

                onPoetryNum = onPoetryNum + 1;
                binding.tvTitle.setText("诗词接龙：" + "(" + onPoetryNum + ")");
            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(PoetryRelayActivity.this, BottomNavigationViewActivity.class);
                intent.putExtra("id",1);
                startActivity(intent);
            }
        });
    }

    //滑动到最底部
    public void scrollBottom() {
        if (null != mDetailChatAdapter&&null != binding.rv) {
            binding.rv.scrollToPosition(mDetailChatAdapter.getItemCount());
        }
    }
    @SuppressLint("HandlerLeak")
    private Handler mhandler = new Handler() {
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x124:
                    //回应诗句，先判断是否还有诗句
                    List<PoetryInfoBean.PoetryInfo> accordList = new ArrayList<>();
                    for (PoetryInfoBean.PoetryInfo protryBean : Constant.poetryInfos) {
//                        for (String paragraph : protryBean.getPoetryContent()) {
                            if (StringUtils.startsWith(protryBean.getPoetryContent(),chooseText)){
//                                PoetryRelayBean poetryRelayBean = new PoetryRelayBean();
//                                poetryRelayBean.setPoetryStr(paragraph);
                                accordList.add(protryBean);
//                            }
                        }
                    }
                    if (accordList.size()>0){
                        //获取在queryDataList中，不在haveShowList中的参数列表
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                            List<PoetryInfoBean.PoetryInfo> notInList2 = accordList.stream()
                                    .filter(element -> !haveShowList.contains(element))
                                    .collect(Collectors.toList());

                            ResponsePretry(notInList2.get(0));
                            haveShowList.add(notInList2.get(0));
                        }
                    }else {
                        Toast.makeText(PoetryRelayActivity.this,"无数据",Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    private void ResponsePretry(PoetryInfoBean.PoetryInfo mProtryBean){
        mDetailChatAdapter.addItem(mProtryBean);
        scrollBottom();
    }

//    private void initJsonData() {//解析数据
//
//        /**
//         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
//         * 关键逻辑在于循环体
//         *
//         * */
//        String JsonData = new GetJsonDataUtil().getJson(PoetryRelayActivity.this, "protry.json");//获取assets目录下的json文件数据
//
//        allMessageDataList = parseData(JsonData);//用Gson 转成实体
//
//        Log.i(TAG, "initJsonData: "+allMessageDataList.size());
//    }

    public ArrayList<ProtryBean> parseData(String result) {//Gson 解析
        ArrayList<ProtryBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                ProtryBean entity = gson.fromJson(data.optJSONObject(i).toString(), ProtryBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return detail;
    }

    @Override
    protected void onDestroy() {
        mhandler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }

}